﻿using fabao.Common.Entity;
using Fabao.Shared.WebApi.Fliters;
using Member.Domain.Entities;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Data;
using System.Domain.Entities;
using System.Security.Claims;
using Wk.System.Domain.Services;

namespace tianzedianzi.Controllers
{
    public class BaseController : Controller
    {
        //public AdminUser adminUser => HttpContext.GetAuthUser();
        protected AdminUser adminUser { get; private set; }
        public List<Menu> ButtonList;
        public BaseController()
        {
          
        }
        // GET: Base
        /// <summary>
        /// 验证是否需要登录
        /// </summary>
        /// <param name="filterContext"></param>
        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            if (User.Identity.IsAuthenticated)
            {
                var userId = User.FindFirstValue("UserId");
                string info = User.Claims.FirstOrDefault()?.Value;
                if (!string.IsNullOrEmpty(info))
                {
                    // 从缓存或数据库获取用户信息
                    adminUser= JsonConvert.DeserializeObject<AdminUser>(info);
                }
            }
            //base.OnActionExecuting(filterContext);
            await next();
            //验证需否需要登录鉴权
            bool NoNeedLogin = ((ControllerActionDescriptor)filterContext.ActionDescriptor).MethodInfo.GetCustomAttributes(false).Any(f => f is NoLoginAttribute);
            if (!NoNeedLogin)
            {
                //获取后台用户缓存信息
                if (adminUser != null)
                {
                    string rawUrl = filterContext.HttpContext.Request.GetDisplayUrl();
                    string requestPath = Request.Path;
                    if (rawUrl.Contains("Index"))
                    {
                        var menuService = HttpContext.RequestServices.GetRequiredService<MenuService>();
                        ButtonList =await menuService.GetButtonlist(rawUrl, 2, adminUser.roleId);
                        if (ButtonList.Count == 0)
                        {
                            ButtonList = await menuService.GetButtonlist(requestPath, 2, adminUser.roleId);
                        }
                    }
                }
                else
                {
                    filterContext.Result = new EmptyResult();
                    const string url = "<script>top.location.href='/Login/LoginOut'</script>";
                    filterContext.HttpContext.Response.WriteAsync(url);
                }
            }
            if (ButtonList!=null)
            {
                base.ViewBag.ButtonList = ButtonList;
            }
        }
      
        protected ActionResult Success(string message = "操作成功", object data = null)
        {
            return Json(new AjaxResult(ResultType.Success, message, data));
        }
        protected ActionResult Error(string message = "对不起，操作失败", object data = null)
        {
            return Json(new AjaxResult(ResultType.Error, message, data));
        }
        protected ActionResult LayuiPageList(string message = "获取数据", object data = null, int count = 0, object odata = null)
        {
            return Json(new AjaxDataListResult(ResultType.Info, message, data, count, odata));
        }
    }
}
